package com.marvels.system.common.filter;

import com.marvels.system.common.dto.FilterConfigDTO;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 
 * @ClassName: RequestCrossFilter
 * @Description: 允许跨域请求
 * @author 李瑶
 * @date 2018年1月16日 上午10:29:43
 *
 */
//@Component
//@WebFilter(filterName = "requestCrossFilter", urlPatterns = "/*")
public class RequestCrossFilter implements Filter {

	@Autowired
	private FilterConfigDTO fiterConfig;

	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
			throws IOException, ServletException {
		String allowOrigin = fiterConfig.getAllowOrigin();
		String allowMethods = fiterConfig.getAllowMethods();
		String allowCredentials = fiterConfig.getAllowCredentials();
		String allowHeaders = fiterConfig.getAllowHeaders();
		String exposeHeaders = fiterConfig.getExposeHeaders();

		HttpServletResponse response = (HttpServletResponse) res;
//		if (StringHelper.isNotEmpty(allowOrigin)) {
			if (allowOrigin==null || "all".equals(allowOrigin)) {
				response.setHeader("Access-Control-Allow-Origin", "*");
			} else {
				response.setHeader("Access-Control-Allow-Origin", allowOrigin);
			}
//		}
		if (StringUtils.isNotEmpty(allowMethods)) {
			response.setHeader("Access-Control-Allow-Methods", allowMethods);
		}
		if (StringUtils.isNotEmpty(allowCredentials)) {
			response.setHeader("Access-Control-Allow-Credentials", allowCredentials);
		}
//		if (StringHelper.isNotEmpty(allowHeaders)) {
			response.setHeader("Access-Control-Allow-Headers", allowHeaders);
//		}
		if (StringUtils.isNotEmpty(exposeHeaders)) {
			response.setHeader("Access-Control-Expose-Headers", exposeHeaders);
		}
		chain.doFilter(req, res);

	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub

	}

}
